import {ChangeDetectorRef, Component, forwardRef, Inject, Input, OnInit, } from '@angular/core';

import {NzMessageService, UploadChangeParam} from 'ng-zorro-antd';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {Observable, Observer} from 'rxjs';
import {DomSanitizer} from '@angular/platform-browser';

@Component({
    selector: 'base-icon-upload',
    templateUrl: './base-icon-upload.component.html',
    styleUrls: ['./base-icon-upload.component.less'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => BaseIconUploadComponent),
            multi: true
        }
    ]
})

export class BaseIconUploadComponent implements OnInit, ControlValueAccessor {

    @Input() maxFileSize = 1024 * 1024;

    @Input()
    valueChange: (value: string | string[] | object) => any;

    fileType: string[] = ['image/jpeg', 'image/png', 'image/jpgv', 'image/jpg', 'image/svg+xml'];

    accept = '.jpeg,.png,.jpg,.svg';
    iconType;
    changeFn = undefined;

    constructor(
        public message: NzMessageService,
        private sanitizer: DomSanitizer,
        @Inject(ChangeDetectorRef) public readonly cd: ChangeDetectorRef) {
    }

    _value;

    get value() {
        return this._value;
    }

    set value(value: any) {
        this._value = value;
        if (this.changeFn) {
            this.changeFn(value);
        }
    }

    ngOnInit(): void {

    }

    // 自定义提交
    customUpload(item) {
        const reader = new FileReader();
        if (item.file.type.indexOf('svg+xml') >= 0) {
            reader.readAsText(item.file, 'utf-8');
            reader.onload = () => {
                this.iconType = 'svg';
                const text = reader.result as string;
                this.value = '<svg' + text.split('<svg')[1];
            };
        } else {
            reader.readAsDataURL(item.file);
            reader.onload = () => {
                this.iconType = 'base64';
                this.value = reader.result as string;
            };
        }
    }

    beforeUpload(file: File) {
        return new Observable((observer: Observer<boolean>) => {
            const isJPG = this.fileType.indexOf(file.type) >= 0;
            if (!isJPG) {
                this.message.info('不支持该格式文件上传');
                return;
            }
            if (file.size > this.maxFileSize) {
                this.message.info('图标大小超过限定值 , 不支持上传');
                return;
            }
            observer.next(isJPG);
        });
    }

    handleChange(info: UploadChangeParam): void {
        if (info.file.status === 'done' && info.file.response.success) {
            this.value = info.file.response.message;
        }
    }

    getSvgHtml(picture: string) {
        return this.sanitizer.bypassSecurityTrustHtml(picture);
    }

    registerOnChange(fn: any): void {
        this.changeFn = fn;
    }

    registerOnTouched(fn: any): void {
    }

    setDisabledState(isDisabled: boolean): void {

    }

    writeValue(_value: any): void {
        this.value = _value;
        if (this._value) {
            this.iconType = this._value.indexOf('svg') >= 0 ? 'svg' : 'base64';
        }
    }
}
